package main

import (
	"bytes"
	"encoding/binary"
	"github.com/golang/protobuf/proto"
)

var enterRoomModuleCommand = [2]byte{109, 1}
var frameSyncReq = [2]byte{109, 4}
var frameSyncPush = [2]int8{109, -4}

type MessageModel struct {
	Length  int32
	Module  byte
	Command byte
	Body    []byte
}

// 是否是帧同步指令
func (messageModel *MessageModel) isFrameSyncCommand() bool {
	return messageModel.Module == frameSyncReq[0] && messageModel.Command == frameSyncReq[1]
}

// 是否是进入房间指令
func (messageModel *MessageModel) isEnterRoomCommand() bool {
	return messageModel.Module == enterRoomModuleCommand[0] && messageModel.Command == enterRoomModuleCommand[1]
}
// 解析玩家进入房间指令
func (messageModel *MessageModel) parseEnterRoomMessage() (*PlayerEnterRoom, error) {
	playerEnterRoom := &PlayerEnterRoom{}
	err := proto.Unmarshal(messageModel.Body, playerEnterRoom)
	if err != nil {
		logger.Println("[ERR] parseEnterRoomMessage: ", err)
		return nil, err
	}
	return playerEnterRoom, nil
}

// 读取数据缓冲区
func (messageModel *MessageModel) read(dataBuffer *bytes.Buffer) {
	var length int32
	var module byte
	var command byte

	err := binary.Read(dataBuffer, binary.BigEndian, &length)

	if err != nil {
		logger.Println("[ERR] Read 获取length失败: ", err)
		return
	}
	err = binary.Read(dataBuffer, binary.BigEndian, &module)
	if err != nil {
		logger.Println("[ERR] Read 获取module失败: ", err)
		return
	}
	err = binary.Read(dataBuffer, binary.BigEndian, &command)
	if err != nil {
		logger.Println("[ERR] Read 获取command失败: ", err)
		return
	}

	body := make([]byte, length-2)
	_, err = dataBuffer.Read(body)
	if err != nil {
		logger.Println("[ERR] Read 获取body失败: ", err)
		return
	}

	messageModel.Length = length
	messageModel.Module = module
	messageModel.Command = command
	messageModel.Body = body
}
